package handlers

import (
	"github.com/6tail/lunar-go/calendar"
	"github.com/gin-gonic/gin"
	"net/http"
	"sanrenx.com/xyxf/app/services"
	"sanrenx.com/xyxf/pkg/app"
	"sanrenx.com/xyxf/pkg/e"
	"time"
)

// @Tags 用户
// @Summary 用户详情
// @Accept application/json
// @Produce json
// @Success 200 {object} app.Response
// @Router  /app/v2/user/info/details [get]
func UserGetDetailsV2(c *gin.Context) {
	appG := app.Gin{C: c}
	//用户登录
	uid, err := appG.GetUID()
	if err != nil {
		appG.Response(http.StatusUnauthorized, e.ErrorAuth, nil)
		return
	}

	//获取详情
	var userSrv services.UserSrv
	if userInfo, err := userSrv.GetUserById(uid); err == nil {
		nowTime := calendar.NewSolarFromDate(time.Now())
		dailyInfo, _ := userSrv.GetStdDaily(uid, nowTime.ToYmd())
		//返回信息
		appG.Response(http.StatusOK, e.SUCCESS, map[string]interface{}{
			"info":  userInfo,
			"daily": dailyInfo,
		})
		return
	}

	appG.Response(http.StatusInternalServerError, e.ErrorAuth, nil)
}

// @Tags 用户
// @Summary 获取日修行记录
// @Accept application/json
// @Produce json
// @Param ymd query string true "日期"
// @Success 200 {object} app.Response
// @Router  /app/v2/user/std/daily [get]
func UserStdDaily(c *gin.Context) {

	var (
		userSrv services.UserSrv
		params  struct {
			Ymd string `form:"ymd" binding:"required,string"`
		}
	)

	appG := app.Gin{C: c}
	//用户登录
	uid, err := appG.GetUID()
	if err == nil {
		appG.Response(http.StatusUnauthorized, e.ErrorAuth, nil)
		return
	}

	//获取数据
	if res, err := userSrv.GetStdDaily(uid, params.Ymd); err == nil {
		//返回信息
		appG.Response(http.StatusOK, e.SUCCESS, res)
		return
	}

	appG.Response(http.StatusInternalServerError, e.ErrorAuth, nil)
}

// @Tags 用户
// @Summary 今日签到
// @Accept application/json
// @Produce json
// @Success 200 {object} app.Response
// @Router  /app/v2/user/std/sign [post]
func UserSignToday(c *gin.Context) {

	appG := app.Gin{C: c}
	//用户登录
	uid, uErr := appG.GetUID()
	if uErr != nil {
		appG.Response(http.StatusUnauthorized, e.ErrorAuth, nil)
		return
	}

	var userSrv services.UserSrv
	//签到
	code, data, err := userSrv.SaveUserSign(uid)
	if err != nil {
		//返回信息
		appG.Response(http.StatusBadRequest, code, nil)
		return
	}

	//****************刷新缓存********************//
	//刷新用户信息缓存
	_, _ = userSrv.RefreshCacheUserById(uid)
	//刷新日常缓存
	nowTime := calendar.NewSolarFromDate(time.Now())
	_, _ = userSrv.RefreshCacheUserDaily(uid, nowTime.ToYmd())
	//================刷新缓存 end================//

	//返回结果和奖励
	appG.Response(http.StatusOK, e.SUCCESS, data)
}
